package com.example.blog.repository;

import com.example.blog.entity.Article;
import com.example.blog.entity.Category;
import com.example.blog.entity.Tag;
import com.example.blog.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface ArticleRepository extends JpaRepository<Article, Long> {
    Page<Article> findByPublishedTrue(Pageable pageable);
    Page<Article> findByAuthor(User author, Pageable pageable);
    
    @Query("SELECT a FROM Article a WHERE a.published = true AND " +
           "(LOWER(a.title) LIKE LOWER(CONCAT('%', ?1, '%')) OR " +
           "LOWER(a.content) LIKE LOWER(CONCAT('%', ?1, '%')))")
    Page<Article> searchArticles(String keyword, Pageable pageable);
    
    List<Article> findTop5ByPublishedTrueOrderByViewCountDesc();
    List<Article> findTop5ByPublishedTrueOrderByCreatedAtDesc();

    Page<Article> findByCategoriesContainingAndPublishedTrue(Category category, Pageable pageable);
    Page<Article> findByTagsContainingAndPublishedTrue(Tag tag, Pageable pageable);

    @Query("SELECT a FROM Article a WHERE a.published = true AND " +
           "EXISTS (SELECT 1 FROM a.categories c WHERE c IN " +
           "(SELECT ac.categories FROM Article ac WHERE ac.id = ?1)) AND " +
           "a.id != ?1 ORDER BY a.viewCount DESC")
    List<Article> findRelatedArticles(Long articleId, Pageable pageable);
} 